$(function () {
    $(".add_to_cart").click(function () {
        // alert("add_to_cart");
        var p_id = $(this).attr("p_id");
        var quantity = $("#quantity").val();
        if (!quantity) {
            quantity = 1
        }
        params = {
            "p_id": p_id,
            "quantity": quantity
        };
        $.ajax({
            url: "/add_to_cart.html",
            type: "post",
            data: JSON.stringify(params),
            contentType: "application/json",
            success: function (resp) {
                if (resp.errno == 0) {
                    var count = $("#count_in_cart").text();
                    $("#count_in_cart").text(parseInt(count) + 1);
                    product = resp.product;
                    product_html = '';
                    product_html += '<div class="dropdown-item d-flex align-items-start" href="#">';
                    product_html += '<div class="img" style="background-image:url(' + product.img_url + ');"></div>';
                    product_html += '<div class="text pl-3">';
                    product_html += '<h4>' + product.name + '</h4>';
                    product_html += '<p class="mb-0"><a href="#" class="price">$' + product.price + '</a><span class="quantity ml-3" p_id="' + product.id + '">Quantity: ' + product.cart + '</span></p>';
                    product_html += '</div></div>';
                    $('.dropdown-menu-right').prepend(product_html);


                } else if (resp.errno == 1) {
                    product = resp.product;
                    id = product.id;
                    $(".quantity.ml-3[p_id=" + id + ']').text("Quantity: " + product.cart)
                } else {
                    alert(resp.errmsg)
                }

            }

        })
    });

    // 现在购买
    $("#buy_now").click(function () {
        p_id = $(this).attr("p_id");
        quantity = $("#quantity").val();
        params = {
            "p_id": p_id,
            "quantity": quantity,
            "is_single": "true"
        };
        $.ajax({
            url: "/get_single_data.html",
            type: "post",
            data: JSON.stringify(params),
            contentType: "application/json",
            success: function (resp) {
                if (resp.errno == 0) {
                    window.location.href = '/checkout.html'
                }

            }
        })

    })
});